<template>
  <div class="common-wrap">
    <div class="data-container">
      <div class="left-tree" :style="{ width: width + 'px' }">
        <div style="padding: 10px">
          <el-button-group>
            <el-button
              icon="Plus"
              @click="handleAddMain"
              v-hasPermi="['common:dictionary:add']"
              class="el-button-plus"
            />
            <el-button
              :disabled="!subOptions.id"
              icon="Edit"
              v-hasPermi="['common:dictionary:edit']"
              @click="handleEditMain"
            />
            <el-button
              :loading="deleteMainLoading"
              :disabled="!subOptions.id"
              v-hasPermi="['common:dictionary:delete']"
              icon="Delete"
              @click="handleMainDelete()"
            />
          </el-button-group>
        </div>
        <WebsiteTree
          :tree-cus-data="treeData"
          :cus-height="50"
          :width="250"
          :checked-row-keys="[]"
          @handle-node-click="handleNodeClick"
        />
        <div ref="dragLine" class="dragLine"></div>
      </div>
      <div class="right-table con-margin-l">
        <div class="common-box">
          <div class="con-button-rows">
            <el-button-group style="margin-right: 10px">
              <el-button
                icon="Plus"
                v-hasPermi="['common:dictionary:childAdd']"
                :disabled="!subOptions.mainCode"
                @click="handleInsertTable()"
                class="el-button-plus"
              />
              <el-button
                :loading="deleteLoading"
                :disabled="!multipleSelection.length"
                v-hasPermi="['common:dictionary:childDelete']"
                icon="Delete"
                @click="handleDelete()"
              />
              <el-button
                :loading="saveLoading"
                v-hasPermi="['common:dictionary:childDocumentAdd']"
                icon="DocumentAdd"
                @click="handleSaveEdit('', 2)"
                :disabled="multipleSelection.length === 0"
              />
              <el-button
                :disabled="!subOptions.mainCode"
                :loading="tableLoading"
                icon="Refresh"
                @click="getSubList()"
              />
            </el-button-group>
          </div>
          <MyTable
            ref="commonTable"
            :data-source="dataSource"
            :loading="tableLoading"
            :keep-source="true"
            :changeEditNeedTrigger="false"
            :edit-config="{
              trigger: 'click',
              mode: 'row',
              showStatus: true,
            }"
            :edit-rules="editRules"
            :page-vo="pageVo"
            :columns="columns"
            moduleName="dictionaryData"
            @handle-selection-change="handleSelectionChange"
            @handle-page-change="handlePageChange"
            @handleEditClosed="(row)=>{
              handleSaveEdit(row,2)
            }"
          />
        </div>
      </div>
    </div>
    <!-- 主类别 -->
    <editMain
      v-if="editMainOptions.visible"
      v-model:visible="editMainOptions.visible"
      :edit-data="editMainOptions.editData"
      @handle-success="getMainData"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import i18n from "@/lang/index";
import editMain from "./editMain.vue";
import * as api from "@/api/index";
defineOptions({
  name: "DictionaryData",
});
const width = ref(300);
const tableLoading = ref(false);
const deleteLoading = ref(false);
const deleteMainLoading = ref(false);
const loading = ref(false);
const saveLoading = ref(false);
const columns = ref([
  {
    type: "checkbox",
    width: 50,
    fixed: "left",
    align: "center",
  },
  {
    title: "序号",
    type: "seq",
    width: 60,
    fixed: "left",
  },
  {
    field: "subCode",
    title: "子类别编号",
    filters: [{ data: { type: "text" } }],
    filterRender: {
      name: "FilterInput",
    },
    params: {
      handleSearch: (data) => {
        searchForm.subCode = data;
        handleSearch();
      },
    },
    width: 120,
  },
  {
    field: "subName",
    title: "子类别名称（中）",
    editRender: { attrs: { placeholder: "请输入名称" } },
    slots: { edit: "input_edit" },
    filters: [{ data: { type: "text" } }],
    filterRender: {
      name: "FilterInput",
    },
    params: {
      handleSearch: (data) => {
        searchForm.subName = data;
        handleSearch();
      },
    },
    width: 200,
  },
  {
    field: "subNameEn",
    title: "子类别名称（英）",
    editRender: {},
    slots: { edit: "input_edit" },
    filters: [{ data: { type: "text" } }],
    filterRender: {
      name: "FilterInput",
    },
    params: {
      handleSearch: (data) => {
        searchForm.subNameEn = data;
        handleSearch();
      },
    },
    width: 200,
  },
  {
    field: "subValue",
    title: "值",
    editRender: {},
    slots: { edit: "input_edit" },
  },
  {
    field: "sort",
    title: "排序",
    editRender: {
      props: {
        type: "number",
      },
    },
    slots: { edit: "input_edit" },
  },
  {
    field: "remark",
    title: "备注",
    editRender: {},
    slots: { edit: "input_edit" },
  },
  {
    field: "enableFlag",
    title: "启用标识",
    editRender: {},
    slots: { edit: "switch_edit" },
    params: {
      openValue: "1",
      closeValue: "0",
    },
    formatter: ({ cellValue }) => {
      return cellValue === "1" ? i18n.global.t("启用") : i18n.global.t("禁用");
    },
    width: 150,
  },
]);
let pageVo = reactive({
  total: 0,
  pageSize: 50,
  currentPage: 1,
});
const searchForm = reactive({});
let subOptions = ref({ id: "" });
const dataSource = ref([]);
const treeData = ref([]);
const editRules = reactive({});
const multipleSelection = ref([]);
const editMainOptions = reactive({
  visible: false,
  editData: {},
});
const commonTable = ref();
async function getMainData() {
  loading.value = true;
  try {
    const res = await api.default.system.dictionaryData.mainList();
    treeData.value = res.data.map((item) => ({
      ...item,
      label: `${item.mainName} （${item.mainCode}）`,
    }));
  } finally {
    loading.value = false;
  }
}
async function getSubList() {
  const postForm = {
    ...searchForm,
    pageNum: pageVo.currentPage,
    pageSize: pageVo.pageSize,
  };
  tableLoading.value = true;
  try {
    const res = await api.default.system.dictionaryData.getSubByMain({
      mainCode: subOptions.value.mainCode,
      ...postForm,
    });
    dataSource.value = res.rows;
    pageVo.total = res.total;
  } finally {
    tableLoading.value = false;
  }
}
function handleSearch() {
  pageVo.currentPage = 1;
  getSubList();
}
function handleSelectionChange(val) {
  multipleSelection.value = val;
}
function handlePageChange(val) {
  const { currentPage, pageSize } = val;
  pageVo.currentPage = currentPage;
  pageVo.pageSize = pageSize;
  getSubList();
}
function handleNodeClick(val) {
  subOptions.value = { ...val };
  handleSearch();
}
async function handleSaveEdit(row, type) {
  tableLoading.value = true;
  try {
    if (type === 1) {
      await api.default.system.dictionaryData.addEditSub({
        ...row,
      });
    } else if (type === 2) {
      multipleSelection.value.forEach((item) => {
        item.id = item.subCode ? item.id : null;
      });
      let checkRow = row || multipleSelection.value.find((item) => !!item.status);
      const errMap = await commonTable.value.$refs.xGrid
        .validate(checkRow)
        .catch((errMap) => errMap);
      if (errMap) {
        ElMessage.error("校验不通过");
      } else {
        await api.default.system.dictionaryData.addEditSub(
       row ||  multipleSelection.value[0]
        );
      }
    }
    ElMessage.success("保存成功");
    getSubList();
  } catch {
    tableLoading.value = false;
  }
}
async function handleInsertTable(row) {
  const $grid = commonTable.value.$refs.xGrid;
  const record = {
    status: "1",
    enableFlag:'1',
    mainCode: subOptions.value.mainCode,
    mainName: subOptions.value.mainName,
  };
  dataSource.value.unshift(record);
  await $grid.setActiveCell(dataSource.value[0], "subName");
}

function handleAddMain() {
  editMainOptions.editData = {};
  editMainOptions.visible = true;
}

function handleEditMain() {
  editMainOptions.editData = { ...subOptions.value };
  editMainOptions.visible = true;
}
function handleDelete() {
  ElMessageBox.confirm(
    i18n.global.t("是否确定删除选中数据?"),
    i18n.global.t("提示"),
    {
      confirmButtonText: i18n.global.t("确定"),
      cancelButtonText: i18n.global.t("取消"),
    }
  ).then(async () => {
    const otherList = multipleSelection.value.filter(
      (item) => !item.createTime
    );
    const idsList = multipleSelection.value.filter((item) => !!item.createTime);
    dataSource.value.forEach((item, index) => {
      otherList.forEach((it) => {
        if (item.id === it.id) {
          dataSource.value.splice(index, 1);
        }
      });
    });
    const ids = idsList.map((item) => item.id);
    try {
      ids.length > 0
        ? await api.default.system.dictionaryData.deleteSub(ids)
        : "";
      handleSearch();
      deleteLoading.value = false;
    } catch {
      deleteLoading.value = false;
    }
  });
  // .catch(() => {
  //   //
  // });
}
function handleMainDelete() {
  ElMessageBox.confirm(
    i18n.global.t("是否确定删除选中数据?"),
    i18n.global.t("提示"),
    {
      confirmButtonText: i18n.global.t("确定"),
      cancelButtonText: i18n.global.t("取消"),
    }
  )
    .then(async () => {
      deleteMainLoading.value = true;
      try {
        await api.default.system.dictionaryData.deleteMain([
          subOptions.value.id,
        ]);
        getMainData();
        deleteMainLoading.value = false;
      } catch {
        deleteMainLoading.value = false;
      }
    })
    .catch(() => {
      //
    });
}
onMounted(() => {
  getMainData();
});
</script>
<style lang="scss" scoped>
.data-container {
  display: flex;
  height: 100%;
  // position: relative;
}

.left-tree {
  flex-shrink: 0;
  // position: relative;
  // float: left;
  background-color: #fff;
  margin-right: 10px;

  :deep() .vxe-table--main-wrapper {
    max-height: calc(100vh - 200px);
    // overflow-y: scroll;
  }

  :deep() .el-button--mini {
    padding: 6px 8px;
  }
}

.right-table {
  width: calc(100% - 300px);
  background: #fff;
}

.dragLine {
  position: absolute;
  top: 0;
  right: -5px;
  z-index: 100;
  width: 10px;
  height: 100%;
  cursor: col-resize;
}
</style>
